import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/icon.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/data/network/entity/worklog/response/ListWorkLogResponse.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/main.dart';
import 'package:timelines/timelines.dart';

import 'state.dart';

class UploadWorkLogScreenLogic extends GetxController {
  final UploadWorkLogScreenState state = UploadWorkLogScreenState();

  Future<void> refreshWorkLogPage() async {
    LoadingElement.loadingDialog(true);
    _initData(true);
  }

  @override
  void onInit() {
    super.onInit();
    _initData(false);
  }

  void _initData(bool isRefresh) {
    MyHttpClient.getListWorkLog(null, null).then((value) {
      if (value.code == 200) {
        if (value.data!.records != null) {
          state.listWorkLog.value = value.data!.records!;
        }
        if (isRefresh) Get.back();
      } else {
        Get.back();
        Utils.toastError(value.msg);
      }
    }).onError((error, p) {
      Get.back();
      Utils.toastError(error);
    });
  }

  createWorkLog() {
    Get.toNamed(RouteConfig.createWorkLogScreen);
  }

  seeDetail(Records listWorkLog) {
    Get.bottomSheet(
        Flexible(
          child: Padding(
            padding: const EdgeInsets.all(24.0),
            child: CustomScrollView(
              slivers:[
                  SliverToBoxAdapter(
                    child: ListTile(
                      trailing: IconButton(
                          onPressed: () => _changeWorkLog(listWorkLog),
                          icon: const Icon(
                            IconLight.Iconly_Light_Outline_Edit,
                            size: 24,
                            color: MyColor.primary,
                          )),
                      title: Text(listWorkLog.type == 1
                          ? MyText.xContent.trParams({'x': MyText.morning.tr})
                          : MyText.content),
                      subtitle: Text(listWorkLog.workAhead ?? ' '),
                      subtitleTextStyle: Theme.of(Get.context!)
                          .textTheme
                          .bodyMedium
                          ?.copyWith(
                              color: MyColor.grayScale[500],
                              fontWeight: FontWeight.w400),
                    ),
                  ),
                  SliverVisibility(
                    visible: listWorkLog.type == 1,
                    sliver: SliverToBoxAdapter(
                      child: ListTile(
                        title: Text(
                            MyText.xContent.trParams({'x': MyText.afternoon.tr})),
                        subtitle: Text(listWorkLog.workAfter ?? ''),
                        subtitleTextStyle: Theme.of(Get.context!)
                            .textTheme
                            .bodyMedium
                            ?.copyWith(
                                color: MyColor.grayScale[500],
                                fontWeight: FontWeight.w400),
                      ),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: ListTile(
                      title: const Text(MyText.summary),
                      subtitle: Text(listWorkLog.content ?? ' '),
                      subtitleTextStyle: Theme.of(Get.context!)
                          .textTheme
                          .bodyMedium
                          ?.copyWith(
                              color: MyColor.grayScale[500],
                              fontWeight: FontWeight.w400),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: ListTile(
                      title: const Text(MyText.workPlan),
                      subtitle: Text(listWorkLog.workPlan ?? ' '),
                      subtitleTextStyle: Theme.of(Get.context!)
                          .textTheme
                          .bodyMedium
                          ?.copyWith(
                              color: MyColor.grayScale[500],
                              fontWeight: FontWeight.w400),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: SizedBox(
                      height: 300,
                      child: Timeline(
                        theme: TimelineThemeData(
                            direction: Axis.vertical,
                            color: MyColor.primary[300],
                            nodePosition: 0.1),
                        children: List.generate(listWorkLog.workTimes?.length ?? 0,
                            (int index) {
                          return TimelineTile(
                            node: TimelineNode(
                              indicator: const DotIndicator(),
                              startConnector: index != 0
                                  ? DecoratedLineConnector(
                                      decoration: BoxDecoration(
                                        gradient: LinearGradient(
                                          begin: Alignment.topCenter,
                                          end: Alignment.bottomCenter,
                                          colors: [
                                            MyColor.gradientBlue[0]!,
                                            MyColor.gradientBlue[1]!
                                          ],
                                        ),
                                      ),
                                    )
                                  : null,
                              endConnector:
                                  index == (listWorkLog.workTimes?.length ?? 1) - 1
                                      ? null
                                      : DecoratedLineConnector(
                                          decoration: BoxDecoration(
                                            gradient: LinearGradient(
                                              begin: Alignment.topCenter,
                                              end: Alignment.bottomCenter,
                                              colors: [
                                                MyColor.gradientBlue[1]!,
                                                MyColor.gradientBlue[0]!
                                              ],
                                            ),
                                          ),
                                        ),
                            ),
                            contents: Container(
                              margin: const EdgeInsets.only(left: 24),
                              padding: const EdgeInsets.all(8),
                              child: Card(
                                child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    children: [
                                      Text(
                                          listWorkLog
                                                  .workTimes![index].projectName ??
                                              '',
                                          style: Theme.of(Get.context!)
                                              .textTheme
                                              .bodyMedium
                                              ?.copyWith(
                                                fontWeight: FontWeight.w400,
                                              )),
                                      Text(
                                          '${MyText.workTime}: ${listWorkLog.workTimes![index].timeCount}' ??
                                              '',
                                          style: Theme.of(Get.context!)
                                              .textTheme
                                              .bodyMedium
                                              ?.copyWith(
                                                  fontWeight: FontWeight.w400,
                                                  color: MyColor.grayScale[500])),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        isScrollControlled: true,
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void showOperateWorkLog(Records listWorkLog) {
    Get.bottomSheet(
        Wrap(children: [
          Container(
            padding: const EdgeInsets.symmetric(vertical: 2),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () => _deleteWorkLog(listWorkLog),
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    MyText.deleteWorkLog.tr,
                    style: Theme.of(Get.context!).textTheme.bodyLarge,
                  ),
                ],
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(vertical: 2),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () => _changeWorkLog(listWorkLog),
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    MyText.changeWorkLog.tr,
                    style: Theme.of(Get.context!).textTheme.bodyLarge,
                  ),
                ],
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
            width: double.infinity,
            height: 60,
            child: TextButton(
              onPressed: () => Get.back(),
              style: Theme.of(Get.context!).textButtonTheme.style,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    MyText.cancel.tr,
                    style: Theme.of(Get.context!)
                        .textTheme
                        .bodyLarge
                        ?.copyWith(color: MyColor.error),
                  ),
                ],
              ),
            ),
          ),
        ]),
        isDismissible: false,
        shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20))),
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  void _deleteWorkLog(Records listWorkLog) {
    Get.back();
    var createTime = DateTime.parse(listWorkLog.createTime!);
    var now = DateTime.now();
    var difference = now.difference(createTime);
    if (difference.inHours > 24) {
      Utils.toastWarning(MyText.notAllowDeleteWorkLog.tr);
      return;
    }
    _realDeleteWorkLog(listWorkLog);
  }

  void _realDeleteWorkLog(Records listWorkLog) {
    Get.defaultDialog(
        title: MyText.deleteProject.tr,
        titleStyle: Theme.of(Get.context!).textTheme.titleSmall,
        middleText: "${MyText.delete.tr}  ${listWorkLog.content!} ?",
        middleTextStyle: Theme.of(Get.context!).textTheme.bodyLarge,
        onConfirm: () {
          Get.back();
          MyHttpClient.deleteWorkLog(listWorkLog.id.toString()).then((value) {
            if (value.code == 200) {
              refreshWorkLogPage();
            } else {
              Utils.toastError(value.msg);
            }
          }).onError((error, p) {
            Utils.toastError(error);
          });
        },
        textCancel: MyText.cancel.tr,
        textConfirm: MyText.confirm.tr);
  }

  void _changeWorkLog(Records listWorkLog) {
    Get.toNamed(RouteConfig.changeWorkLogScreen,
        arguments: {'data': listWorkLog});
  }
}
